package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.*;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.SurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/surveys")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SurveyController {

    @Autowired
    private SurveyService surveyService;

    /**
     * 创建问卷（管理员）
     */
    @PostMapping
    public CommonResponse<Integer> createSurvey(@RequestBody CreateSurveyDTO createSurveyDTO) {
        try {
            Integer surveyId = surveyService.createSurvey(createSurveyDTO);
            return CommonResponse.createForSuccess(200, "问卷创建成功", surveyId);
        } catch (Exception e) {
            return CommonResponse.createForError(500, "问卷创建失败: " + e.getMessage());
        }
    }

    /**
     * 获取问卷详情
     */
    @GetMapping("/{surveyId}")
    public CommonResponse<SurveyDTO> getSurveyDetail(@PathVariable Integer surveyId) {
        try {
            SurveyDTO survey = surveyService.getSurveyDetail(surveyId);
            if (survey == null) {
                return CommonResponse.createForError(404, "问卷不存在");
            }
            return CommonResponse.createForSuccess(200, "获取问卷详情成功", survey);
        } catch (Exception e) {
            return CommonResponse.createForError(500, "获取问卷详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取问卷列表（分页）
     */
    @GetMapping
    public CommonResponse<PageResponseDTO<SurveyDTO>> getSurveyList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            PageResponseDTO<SurveyDTO> result = surveyService.getSurveyPage(page, size);
            return CommonResponse.createForSuccess(200, "获取问卷列表成功", result);
        } catch (Exception e) {
            return CommonResponse.createForError(500, "获取问卷列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除问卷（管理员）
     */
    @DeleteMapping("/{surveyId}")
    public CommonResponse<Boolean> deleteSurvey(@PathVariable Integer surveyId) {
        try {
            boolean success = surveyService.deleteSurvey(surveyId);
            if (success) {
                return CommonResponse.createForSuccess(200, "问卷删除成功", true);
            } else {
                return CommonResponse.createForError(400, "问卷删除失败");
            }
        } catch (Exception e) {
            return CommonResponse.createForError(500, "问卷删除失败: " + e.getMessage());
        }
    }

    /**
     * 提交问卷答案
     */
    @PostMapping("/{surveyId}/submit")
    public CommonResponse<Boolean> submitSurveyAnswer(
            @PathVariable Integer surveyId,
            @RequestBody Map<String, Object> request) {
        try {
            Integer userId = (Integer) request.get("userId");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> answersData = (List<Map<String, Object>>) request.get("answers");
            
            List<SurveyAnswerDTO> answers = answersData.stream().map(data -> {
                SurveyAnswerDTO answer = new SurveyAnswerDTO();
                answer.setQuestionId((Integer) data.get("questionId"));
                answer.setAnswerText((String) data.get("answerText"));
                return answer;
            }).collect(java.util.stream.Collectors.toList());
            
            boolean success = surveyService.submitSurveyAnswer(surveyId, userId, answers);
            if (success) {
                return CommonResponse.createForSuccess(200, "问卷提交成功", true);
            } else {
                return CommonResponse.createForError(400, "问卷提交失败，可能已经提交过了");
            }
        } catch (Exception e) {
            return CommonResponse.createForError(500, "问卷提交失败: " + e.getMessage());
        }
    }

    /**
     * 获取问卷统计结果（管理员）
     */
    @GetMapping("/{surveyId}/statistics")
    public CommonResponse<Map<String, Object>> getSurveyStatistics(@PathVariable Integer surveyId) {
        try {
            Map<String, Object> statistics = surveyService.getSurveyStatistics(surveyId);
            return CommonResponse.createForSuccess(200, "获取问卷统计成功", statistics);
        } catch (Exception e) {
            return CommonResponse.createForError(500, "获取问卷统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户可填写的问卷列表
     */
    @GetMapping("/available")
    public CommonResponse<List<SurveyDTO>> getAvailableSurveys(
            @RequestParam Integer userId,
            @RequestParam Integer userRole) {
        try {
            List<SurveyDTO> surveys = surveyService.getAvailableSurveys(userId, userRole);
//            System.out.println("surveys " +surveys);
            return CommonResponse.createForSuccess(200, "获取可用问卷成功", surveys);
        } catch (Exception e) {
            return CommonResponse.createForError(500, "获取可用问卷失败: " + e.getMessage());
        }
    }
} 